const JSZIP = require("jszip");
class ZipAssetsPlugin {
  constructor(options) {
    this.filename = options.filename;
  }

  apply(compiler) {
    console.log("ZipAssetsPlugin", this.filename);
    compiler.hooks.emit.tapAsync("ZipAssetsPlugin", async (compilation, cb) => {
      const assets = compilation.assets;
      const zip = new JSZIP();

      for (const filename in assets) {
        // 得到webpack打包后的资源
        const source = assets[filename].source();
        console.log(source, "source");
        zip.file(filename, source);
      }

      const zipBuffer = await zip.generateAsync({
        type: "nodebuffer",
      });
      //通过compiler.webpack.sources可以得到RawSource
      const { RawSource } = compiler.webpack.sources;
      //   将zip生成的buffer交由webpack处理，webpack会在emitAssets的时候，将zipBuffer写到output
      compilation.assets[`${this.filename}.zip`] = new RawSource(zipBuffer);
      console.log(zipBuffer, "zipBuffer");

      //忘记掉下面的这个回调函数，webpack的处理会被中断
      cb();
    });
  }
}

module.exports = ZipAssetsPlugin;
